package com.xianyun.book.command;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.Assert;
import com.xianyun.book.domain.gateway.BookGateway;
import com.xianyun.book.domain.gateway.OrderGateway;
import com.xianyun.book.domain.order.SalesOrder;
import com.xianyun.book.dto.BookSellAddCmd;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author ytt
 */
@Component
public class BookSellAddCmdExe {

    @Resource
    private BookGateway bookGateway;

    @Resource
    private OrderGateway orderGateway;

    public Response execute(@Valid BookSellAddCmd cmd) {
        String bookIsbn = cmd.getIsbn();
        Assert.isTrue(checkBookExist(bookIsbn),"该书籍不存在请添加书籍");
        SalesOrder salesOrder = new SalesOrder();
        salesOrder.setSellId(cmd.getUserSecurity());
        salesOrder.setUserSecurity(cmd.getUserSecurity());
        salesOrder.setBuyer(false);
        salesOrder.setFinenessType(cmd.getFinenessType());
        salesOrder.setIsbn(cmd.getIsbn());
        salesOrder.setSellNumber(cmd.getSellNumber());
        String orderId = orderGateway.createBookSellOrder(salesOrder);
        salesOrder.setSellId(orderId);
        bookGateway.refreshBook(salesOrder);
        return Response.buildSuccess();
    }

    private boolean checkBookExist(String isbn){
        return null != bookGateway.saveOrQueryBookByIsbn(isbn);
    }

}
